package com.distributed.lock.jobs;

import com.distributed.lock.config.impl.EmLock;
import com.distributed.lock.config.impl.LockRangeEnum;
import com.distributed.lock.utils.RedissonUtils;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @program: SpringBootDemos
 * @description:
 * @author: Kangsen
 * @create: 2022-07-14 10:35
 *
 * Job去触发测试一下分布式锁
 *
 **/
@Component
@Slf4j
public class MyJob {

    @Resource
    private RedissonUtils redissonUtils;
    private static final String JOB_LOCK = "job-lock";

    //@Scheduled(cron = "3/8 * * * * ?")
    public void testJob(){
        RLock lock = redissonUtils.tryLockObj(JOB_LOCK, 0, 2);
        if (lock != null) {
            try {
                //说明获取到了锁
                log.info("获取到锁 执行业务");
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if(lock != null && lock.isLocked() && lock.isHeldByCurrentThread()){
                    redissonUtils.unlock(lock);
                }
            }
        }else{
            log.info("没有获取到锁  不执行业务");
        }
    }

    @Scheduled(cron = "0/5 * * * * ?")
    @EmLock(key = "testJobAnnotation",lockRange = LockRangeEnum.APPLICATION)
    public void testJobAnnotation(){
        //说明获取到了锁
        log.info("{} 执行任务！！！！！",Thread.currentThread().getName());
    }
}
